package com.gzu.finalwork.user.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.concurrent.TimeUnit;

@Service
public class AddressStatsService {
    
    @Autowired
    private RedisTemplate<String, Object> redisTemplate;
    
    // Redis键前缀
    private static final String ADDRESS_USAGE_KEY = "address:usage:";
    private static final String ADDRESS_GROWTH_KEY = "address:growth:";
    private static final String USER_ADDRESS_PREFIX = "user:address:";
    private static final String ADDRESS_DETAIL_KEY = "address:detail:";
    
    //记录地址使用
    public void recordAddressUsage(Long userId, String name, String phone, String address) {
        if (address == null || address.trim().isEmpty()) {
            return;
        }

        String currentPeriod = getCurrentPeriod();

        // 创建地址标识（用于Redis存储的key）
        String addressKey = createAddressKey(name, phone, address);

        // 记录总使用次数（永久存储）
        String usageKey = ADDRESS_USAGE_KEY + userId;
        redisTemplate.opsForZSet().incrementScore(usageKey, addressKey, 1.0);

        // 记录当前时间段的增长次数（7天过期）
        String growthKey = ADDRESS_GROWTH_KEY + userId + ":" + currentPeriod;
        redisTemplate.opsForZSet().incrementScore(growthKey, addressKey, 1.0);
        redisTemplate.expire(growthKey, 7, TimeUnit.DAYS);

        // 存储地址详细信息（用于返回时查询）
        String detailKey = ADDRESS_DETAIL_KEY + userId + ":" + addressKey;
        Map<String, String> addressDetail = new HashMap<>();
        addressDetail.put("name", name != null ? name : "");
        addressDetail.put("phone", phone != null ? phone : "");
        addressDetail.put("address", address);
        redisTemplate.opsForHash().putAll(detailKey, addressDetail);
        redisTemplate.expire(detailKey, 30, TimeUnit.DAYS);
    }

    // 创建地址唯一标识
    private String createAddressKey(String name, String phone, String address) {
        return String.format("%s|%s|%s",
                name != null ? name : "",
                phone != null ? phone : "",
                address != null ? address : "");
    }
    
    //获取用户常用地址Top3
    public List<Map<String, Object>> getTopFrequentAddresses(Long userId) {
        String usageKey = ADDRESS_USAGE_KEY + userId;
        String currentPeriod = getCurrentPeriod();
        String growthKey = ADDRESS_GROWTH_KEY + userId + ":" + currentPeriod;

        // 获取所有地址的使用次数
        Set<ZSetOperations.TypedTuple<Object>> usageScores =
                redisTemplate.opsForZSet().reverseRangeWithScores(usageKey, 0, -1);

        // 获取当前时间段的增长次数
        Set<ZSetOperations.TypedTuple<Object>> growthScores =
                redisTemplate.opsForZSet().reverseRangeWithScores(growthKey, 0, -1);

        // 转换为Map便于查找
        Map<String, Double> usageMap = new HashMap<>();
        Map<String, Double> growthMap = new HashMap<>();

        if (usageScores != null) {
            for (ZSetOperations.TypedTuple<Object> tuple : usageScores) {
                usageMap.put((String) tuple.getValue(), tuple.getScore());
            }
        }

        if (growthScores != null) {
            for (ZSetOperations.TypedTuple<Object> tuple : growthScores) {
                growthMap.put((String) tuple.getValue(), tuple.getScore());
            }
        }

        // 计算综合权重：使用次数权重60%，增长次数权重40%
        Map<String, Double> weightedScores = new HashMap<>();
        Set<String> allAddressKeys = new HashSet<>(usageMap.keySet());
        allAddressKeys.addAll(growthMap.keySet());

        for (String addressKey : allAddressKeys) {
            double usageScore = usageMap.getOrDefault(addressKey, 0.0);
            double growthScore = growthMap.getOrDefault(addressKey, 0.0);
            double totalWeight = usageScore * 0.6 + growthScore * 0.4;
            weightedScores.put(addressKey, totalWeight);
        }

        // 按权重排序并取前3个
        List<Map<String, Object>> result = weightedScores.entrySet().stream()
                .sorted(Map.Entry.<String, Double>comparingByValue().reversed())
                .limit(3)
                .map(entry -> {
                    String addressKey = entry.getKey();

                    // 获取地址详细信息
                    String detailKey = ADDRESS_DETAIL_KEY + userId + ":" + addressKey;
                    Map<Object, Object> addressDetail = redisTemplate.opsForHash().entries(detailKey);

                    Map<String, Object> addressInfo = new HashMap<>();
                    addressInfo.put("name", addressDetail.getOrDefault("name", ""));
                    addressInfo.put("phone", addressDetail.getOrDefault("phone", ""));
                    addressInfo.put("address", addressDetail.getOrDefault("address", ""));
                    addressInfo.put("totalWeight", entry.getValue());

                    return addressInfo;
                })
                .toList();

        return result;
    }
    
    // 获取当前时间段标识（按天）
    private String getCurrentPeriod() {
        return LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
    }
    
    // 清理用户地址统计数据
    public void clearUserAddressStats(Long userId) {
        String usageKey = ADDRESS_USAGE_KEY + userId;
        String userKey = USER_ADDRESS_PREFIX + userId;
        redisTemplate.delete(usageKey);
        redisTemplate.delete(userKey);

        // 清理增长数据（需要遍历可能的时间段）
        String growthPattern = ADDRESS_GROWTH_KEY + userId + ":*";
        Set<String> growthKeys = redisTemplate.keys(growthPattern);
        if (growthKeys != null && !growthKeys.isEmpty()) {
            redisTemplate.delete(growthKeys);
        }
    }
}